package com.yzh.wanandroid.component.fragment

import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yzh.wanandroid.R
import com.yzh.wanandroid.adapter.ProjectArticleListAdapter
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.databinding.FragmentProjectArticleBinding
import com.yzh.wanandroid.network.retrofit.responsebean.TitleData
import com.yzh.wanandroid.vm.ProjectArticleFragmentVm
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class ProjectArticleFragment(var projectArticleTitle: TitleData) :
    MvvmFragment<FragmentProjectArticleBinding, ProjectArticleFragmentVm>() {

    private val TAG = "ProjectArticleFragment"

    override fun initViewModel(): ProjectArticleFragmentVm = createViewModel()

    private val mAdapter by lazy { ProjectArticleListAdapter() }

    override fun getLayoutId() = R.layout.fragment_project_article

    override fun initView(view: View) {
        initRecyclerView()
        initSwipeRefresh()
    }

    override fun onLazyLoad() {
        super.onLazyLoad()
        loadProjectArticleData()
    }

    override fun initData() {
        ininBinding()
        Log.i(TAG,"initData projectArticleTitle = $projectArticleTitle")
    }

    private fun ininBinding() {
        mBinding.run {
            netWorkData = mViewModel.netWorkData
            adapter = mAdapter
            refreshData = mAdapter.refreshData
            fragment = this@ProjectArticleFragment
        }
    }

    private fun initRecyclerView() {
        mBinding.run {
            var linearLayoutManager = LinearLayoutManager(requireActivity())
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            projectArticleList.layoutManager = linearLayoutManager
        }
    }

    /**
     * 初始化 SwipeRefreshLayout
     */
    private fun initSwipeRefresh() {
        mBinding.run {
            projectArticleSwipeRefresh.setColorSchemeResources(R.color.color_main)
            projectArticleSwipeRefresh.setOnRefreshListener { initData() }
        }
    }

    private fun loadProjectArticleData() {
        lifecycleScope.launch {
            try {
                mViewModel.getData(projectArticleTitle.id).collectLatest {
                    Log.i(TAG,"loadProjectArticleData it = $it")
                    mAdapter.submitData(it)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun onReloadClick() {

    }
}